package com.yvon.maple.auth.authorization.oauth2.enhancer;

import com.google.common.collect.Maps;
import com.yvon.maple.auth.authorization.model.SecurityUser;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.Map;

import static com.yvon.maple.constants.SystemConstant.Common.STR_ID;
import static com.yvon.maple.constants.SystemConstant.Common.STR_USER_ID;
import static com.yvon.maple.constants.SystemConstant.Common.STR_ORGANIZATION;

/**
 * 自定义token携带内容
 */
public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Map<String, Object> additionalInfo = Maps.newHashMap();
        if(authentication.getPrincipal().toString().contains(STR_ID)) {
            SecurityUser user = (SecurityUser) authentication.getPrincipal();
            additionalInfo.put(STR_USER_ID, user.getId());
        }
        additionalInfo.put(STR_ORGANIZATION, authentication.getName());
        ((DefaultOAuth2AccessToken) accessToken)
                .setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}
